package cn.wp.order.controller;

import cn.wp.order.service.IProductOrderService;
import cn.wp.basic.util.AjaxResult;
import cn.wp.user.domain.LoginInfo;
import cn.wp.user.domain.User;
import cn.wp.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class ProductOrderController {

    @Autowired
    private IProductOrderService productOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 创建订单
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/createOrder")
    public AjaxResult submit(@RequestBody Map<String,String> params, HttpServletRequest request){
        try {
            // 获取token
            String token = request.getHeader("TOKEN");
            LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
            System.out.println(loginInfo.getId());
            // 根据登录用户id查询用户对象
            User user = userService.loadByLoginInfoId(loginInfo.getId());

            String result =  productOrderService.createOrder(params,user);
            System.out.println(result);
            return AjaxResult.me().setResultObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }
    }
}
